package com.example.security.provisioning;

import com.example.security.auth.UserServiceImpl;
import com.example.security.auth.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @className: MysqlUserDetailsManager
 * @author: YTF
 * @date: 2025/4/30 9:18
 * @description:
 */
@Service
public class CustomUserDetailsManager extends InMemoryUserDetailsManager {

    @Autowired
    private UserServiceImpl userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Users users = userMapper.getUserByUsername(username);
        if (users == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }

        List<String> authorities = users.getAuthorities();
        // 将 List 转换为 String 数组
        String[] array = authorities.toArray(new String[0]);
        // 构建 UserDetails 对象
        return User.builder()
                .username(users.getUsername())
                .password(users.getPassword())
                .roles(array)
                .build();
    }

}

